//
//  TWAnimationViewController.swift
//  EyepetizerImitative
//
//  Created by 田伟 on 2017/3/31.
//  Copyright © 2017年 个人. All rights reserved.
//  相关页

import UIKit

class TWAnimationViewController: UIViewController {
    
    // MARK:- 懒加载
    fileprivate lazy var headerView : TWAnimationHeaderView = TWAnimationHeaderView()
    fileprivate lazy var backgroundImageView : UIImageView = UIImageView()
    fileprivate lazy var dismissButton : UIButton = UIButton()
    fileprivate lazy var tableView : UITableView = UITableView()
//    fileprivate lazy var videoView: TWSmallVideoPlayerView = TWSmallVideoPlayerView(frame: CGRect(x: 0, y: 0, width: TWScreenWidth, height: VideoCellHeight))
    
    // 显示在最上
    fileprivate lazy var scaleView : TWScaleView = TWScaleView(frame: CGRect(x: 0, y: 0, width: TWScreenWidth, height: VideoCellHeight))

    
    // MARK:- 属性
    var itemModel : TWItemModel?{
        didSet{
            guard let itemModel = itemModel else {
                return
            }
            // 视频播放器赋值
//            videoView.palyModel = itemModel
            scaleView.model = itemModel

            // tableView的头部赋值
            headerView.itemModel = itemModel
            headerView.frame = CGRect(x: 0, y: 0, width: TWScreenWidth, height: headerView.headerHeight)
            
            // tableView的cell请求数据
            tw_id = itemModel.id?.stringValue
            loadCorrelationData(tw_id: tw_id)
        }
    }
    var tw_id : String?
    // 数据源
    var correlationArray = [TWCorrelationModel]()
    
    // MARK:- 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.black
        setupBackgroundImageView()
        setuptableView()
        setupScaleView()
        setupDismissButton()
        setupNoticationCenter()
    }
    deinit {
        print("详情页内存释放掉了⭐️")
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK:- 加载数据
extension TWAnimationViewController {
    fileprivate func loadCorrelationData(tw_id : String?){
        correlationArray.removeAll()
        let correlationUrl = "https://baobab.kaiyanapp.com/api/v3/video/\(tw_id!)/detail/related?_s=935fbb69b0f051eff330ca3b680d9aa8&f=iphone&net=wifi&p_product=EYEPETIZER_IOS&u=27e73f129dc6a90ed0b2da2cb1c8b3d14829761d&v=3.3.0&vc=2412"
        TWNetworkTool.shareInstance.loadCorrelationData(urlString: correlationUrl) { [weak self](result, error) in
            if error != nil {
                return
            }
            guard let result = result else {
                return
            }
            for item in result {
                let type = item["type"] as! String
                if type == "videoCollectionWithTitle" {
                    let corrrlationModel = TWCorrelationModel(dict: item["data"] as! [String : AnyObject])
                    self?.correlationArray.append(corrrlationModel)
                }
            }
            self?.tableView.reloadData()
        }
    }
}

// MARK:- UI界面
extension TWAnimationViewController {
    fileprivate func setupScaleView(){
//        scaleView.frame = CGRect(x: 0, y: 0, width: TWScreenWidth, height: VideoCellHeight)
        scaleView.scaleViewDelegate = self
        scaleView.clipsToBounds = true
        view.addSubview(scaleView)
    }
    fileprivate func setupDismissButton(){
        dismissButton.setImage(UIImage(named: "ic_video_dismiss_30x30_"), for: .normal)
        dismissButton.addTarget(self, action: #selector(dismissButtonDidClick), for: .touchUpInside)
        dismissButton.frame = CGRect(x: 10, y: 20, width: 30, height: 30)
        view.addSubview(dismissButton)
    }
    fileprivate func setupBackgroundImageView(){
        backgroundImageView = UIImageView(frame: CGRect(x: 0, y: 20, width: view.frame.width, height: view.frame.height))
        backgroundImageView.sd_setImage(with: URL(string: (itemModel?.cover?.blurred)!))
        view.addSubview(backgroundImageView)
    }
    fileprivate func setuptableView(){
        tableView.frame = UIScreen.main.bounds
        tableView.backgroundColor = UIColor.clear
        tableView.contentInset = UIEdgeInsets(top: VideoCellHeight, left: 0, bottom: 0, right: 0)
        tableView.tableHeaderView = headerView
        view.addSubview(tableView)
        tableView.separatorStyle = .none
        tableView.register(UINib(nibName: "TWCorrelationCell", bundle: nil), forCellReuseIdentifier: CorrelationCell)
        tableView.dataSource = self
        tableView.delegate = self
        
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 150))
        footerView.backgroundColor = UIColor.clear
        tableView.tableFooterView = footerView
        let footerLabel = UILabel()
        footerLabel.text = "- The End -"
        footerLabel.textColor = UIColor.white
        footerLabel.font = UIFont(name: "Lobster 1.4", size: 14)
        footerLabel.sizeToFit()
        footerView.addSubview(footerLabel)
        footerLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(footerView)
            make.centerY.equalTo(footerView)
        }
    }
}

// MARK:- --代理方法--
// MARK:- --UITableView代理--
extension TWAnimationViewController : UITableViewDataSource , UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return correlationArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CorrelationCell, for: indexPath) as! TWCorrelationCell
        let model = correlationArray[indexPath.row]
        cell.selectionStyle = .none
        cell.correlationModel = model
        cell.correlationCellDelegate = self
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = correlationArray[indexPath.row]
        let count = model.itemList?.count
        if let count = count {
            return CGFloat(count) * 120 + 60
        }
        return 0
    }
}

// MARK:- --TWCorrelationCellDelegate代理--
extension TWAnimationViewController : TWCorrelationCellDelegate {
    func correlationCellAboutButtonDidClick(correlationModel: TWCorrelationModel) {
        let str = correlationModel.header?.title
        TWLog(message: str!)
    }
}


extension TWAnimationViewController : scaleViewDelegate {
    func scaleViewPlayButtonClick(model: TWItemModel) {
        let videoPlayVc = TWVideoPlayerController()
        videoPlayVc.palyModel = model
        present(videoPlayVc, animated: true) {
            UIApplication.shared.keyWindow?.addSubview(videoPlayVc.view)
        }
    }
}

// MARK:- 接受通知
extension TWAnimationViewController {
    fileprivate func setupNoticationCenter(){
        NotificationCenter.default.addObserver(self, selector: #selector(animationHeaderViewShowMoreButtonClick), name: NSNotification.Name(rawValue :AnimationHeaderViewShowMoreButtonClickNotification), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(correlationCellDidSeleted(note:)), name: NSNotification.Name(rawValue: CorrelationCollectionViewCellDidSeleted), object: nil)
    }
}

// MARK:- 监听点击
extension TWAnimationViewController {
    @objc fileprivate func animationHeaderViewShowMoreButtonClick(){
        headerView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: headerView.headerHeight)
        tableView.reloadData()
    }
    @objc fileprivate func dismissButtonDidClick(){
        // 销毁视频播放器
//        videoView.dismissSmallVideoPlayer()
        dismiss(animated: true, completion: nil)
    }
    @objc fileprivate func correlationCellDidSeleted(note : NSNotification){

        let newItemModel = note.object as! TWItemModel // 拿到当前选中的模型
        itemModel = newItemModel
    
        // 刷新更改为新的model数据
        tableView.alpha = 0
        // 重设偏移值
        self.tableView.contentOffset = CGPoint(x: 0, y: -(VideoCellHeight + self.headerView.frame.height))
        UIView.animate(withDuration: 0.25, animations: {
            self.tableView.reloadData()
        }) { (_) in
            self.tableView.alpha = 1
        }
    }
}
